package com.wtwd.device.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtwd.device.dao.HealthTypeMapper;
import com.wtwd.device.model.entity.HealthType;
import com.wtwd.device.model.vo.HealthTypeVo;
import com.wtwd.device.model.vo.UploadFileVO;
import com.wtwd.device.service.FileService;
import com.wtwd.device.service.HealthTypeContentService;
import com.wtwd.device.service.HealthTypeService;
import com.wtwd.device.service.RedisService;
import com.wtwd.device.util.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2023-08-16
 */
@Service
public class HealthTypeServiceImpl extends ServiceImpl<HealthTypeMapper, HealthType> implements HealthTypeService {


    @Value("${healthType.excel}")
    private String healthTypePath;

    @Value("${file.path}")
    private String filePath;

    @Value("${healthContent.excel}")
    private String healthContentPath;

    @Value("${file.http}")
    private String fileHttp;

    @Value("${healthType.images}")
    private String healthTypeImages;

    @Resource
    private HealthTypeMapper healthTypeMapper;

    @Resource
    private HealthTypeContentService healthTypeContentService;

    @Resource
    private RedisService redisService;

    @Resource
    private FileService fileService;


    @Override
    public IPage queryPage(Page<HealthType> page, HealthType healthType) {
        Page healthTypePage = new LambdaQueryChainWrapper<>(healthTypeMapper)
                .like(StringUtils.isNotBlank(healthType.getName()), HealthType::getName, healthType.getName())
                .page(page);
        if (healthTypePage.getRecords() != null && healthTypePage.getRecords().size() > 0) {
            ArrayList<HealthTypeVo> healthTypeVos = new ArrayList<>();
            healthTypePage.getRecords().stream().forEach(
                    e -> {
                        HealthType e1 = (HealthType) e;
                        HealthTypeVo healthTypeVo = new HealthTypeVo();
                        BeanUtils.copyProperties(e1, healthTypeVo);
                        if (StringUtils.isNotBlank(e1.getPath())) {
                            healthTypeVo.setAbsolutelyPath(fileHttp.concat(healthTypePath).concat(e1.getPath()));
                        }
                        if (StringUtils.isNotBlank(e1.getImage())){
                            healthTypeVo.setImageAbsolutelyPath(fileHttp.concat(healthTypeImages).concat(e1.getImage()));
                        }
                        healthTypeVos.add(healthTypeVo);
                    });
            healthTypePage.setRecords(healthTypeVos);
        }
        return healthTypePage;
    }

    @Override
    public boolean authNameIsExist(boolean exclude, String name, Integer key) {
        HealthType healthType = queryHealthTypeByName(name);
        if (healthType == null) {
            return false;
        }
        if (exclude) {
            if (healthType.getId().equals(key)) {
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    @Override
    public HealthType queryHealthTypeByName(String name) {
        if (StringUtils.isBlank(name)) {
            return null;
        }
        return new LambdaQueryChainWrapper<>(healthTypeMapper)
                .eq(HealthType::getName, name)
                .one();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Integer id) {
        boolean rest = healthTypeContentService.deleteByTypeId(id);
        if (rest) {
            redisService.deleteCache(HEATH_TYPE_KEY_PREFIX, id.toString());
            //do 删除文件
            return removeById(id);
        }
        return rest;
    }

    @Override
    public UploadFileVO uploadNationalizedDocument(MultipartFile file, Integer type) {
        String path = "";
        if (HEALTH_TYPE.equals(type)) {
            path = filePath.concat(healthTypePath);
        } else if (HEALTH_CONTENT.equals(type)) {
            path = filePath.concat(healthTypePath);
        }
        File saveFile = new File(path);
        if (!saveFile.exists()) {
            //文件不存在则创建一个
            saveFile.mkdir();
        }
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().concat(originalFilename);
        String filepath = "";
        try {
            FileUtils.uploadFile(path, fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        UploadFileVO uploadFileVO = new UploadFileVO();
        uploadFileVO.setFileUrl(fileName);
        return uploadFileVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insert(HealthType healthType) throws Exception {
        int rest = healthTypeMapper.insert(healthType);
        if (rest > 0) {
            if (StringUtils.isNotBlank(healthType.getPath())) {
                List list = fileService.readExcel(filePath.concat(healthTypePath).concat(healthType.getPath()));
                if (list != null && list.size() > 0) {
                    redisService.saveCache(HEATH_TYPE_KEY_PREFIX, healthType.getId().toString(), JSONObject.toJSONString(list));
                }
            }
        }
        return rest > 0 ? true : false;
    }

    @Override
    public String getCacheHashKey(Integer healthTypeId) {
        return HEATH_TYPE_KEY_PREFIX.concat(healthTypeId.toString());
    }

    /**
     * 更新健康类型
     * 1.如果重新上传文件则覆盖原有缓存值
     * 2.更新健康类型本身数据
     *
     * @param healthType
     * @return
     */
    @Override
    public boolean updateHealthTypeById(HealthType healthType) {
        if (StringUtils.isNotBlank(healthType.getPath())) {
            List list = null;
            try {
                list = fileService.readExcel(filePath.concat(healthTypePath).concat(healthType.getPath()));
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            if (list != null && list.size() > 0) {
                redisService.saveCache(HEATH_TYPE_KEY_PREFIX, healthType.getId().toString(), JSONObject.toJSONString(list));
            }
        }else {//删除缓存
            redisService.deleteCache(HEATH_TYPE_KEY_PREFIX,healthType.getId().toString());
        }
        return updateById(healthType);
    }


}
